package com.ezcoding.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ezcoding.dao.CompanyDao;
import com.ezcoding.dao.FormulaDao;
import com.ezcoding.dao.ProductDao;
import com.ezcoding.dao.UserDao;
import com.ezcoding.model.*;
import com.ezcoding.utils.StatusUtil;
import com.ezcoding.utils.Tools;

import java.util.*;

public class ProductService {
    private static ProductService instance = new ProductService();

    public final static int TYPE_ADD = 0;
    public final static int TYPE_UPDATE = 1;

    public static ProductService getInstance() {
        return instance;
    }

    /**
     * 检查商品列表products中是否存在重复商品
     *
     * @param products 输入的商品列表
     * @return true:存在重复商品 false:不存在重复商品
     */
    private boolean checkRepeatProduct(List<Product> products) {
        Set<String> productIds = new HashSet<>();

        for (Product product : products) {
            productIds.add(product.getProductId());
        }

        return productIds.size() != products.size();
    }

    private Map<String, Object> addOrUpdateProduct(
            int addOrProduct,
            String companyId,
            String productId,
            String type,
            String name,
            String unit,
            String productNum,
            String upperLimitStr,
            String lowerLimitStr,
            String brand,
            String originPlace,
            String specifications,
            String barCode,
            String remark,
            String guidePrice1Str,
            String guidePrice2Str,
            String primaryDirectory,
            String secondaryDirectory) {
        if (Tools.checkParaIsInValidate(companyId, type, name)) {
            return StatusUtil.getFailedStatusWithMessage("参数无效！");
        }

        if (Tools.checkParaIsNullPoint(
                unit,
                productNum,
                upperLimitStr,
                lowerLimitStr,
                brand,
                originPlace,
                specifications,
                barCode,
                remark,
                guidePrice1Str,
                guidePrice2Str,
                primaryDirectory,
                secondaryDirectory)) {
            return StatusUtil.getFailedStatusWithMessage("参数无效！");
        }

        int upperLimit = Tools.parseNatureInteger(upperLimitStr);
        int lowerLimit = Tools.parseNatureInteger(lowerLimitStr);

        if (lowerLimit > upperLimit) {
            return StatusUtil.getFailedStatusWithMessage("上限不能小于下限！");
        }

        upperLimit = upperLimit == -1 ? 0 : upperLimit;
        lowerLimit = lowerLimit == -1 ? 0 : lowerLimit;

        guidePrice1Str = guidePrice1Str.isEmpty() ? "0" : guidePrice1Str;
        guidePrice2Str = guidePrice2Str.isEmpty() ? "0" : guidePrice2Str;

        double guidePrice1 = Tools.parseNonNegativeDouble(guidePrice1Str);
        double guidePrice2 = Tools.parseNonNegativeDouble(guidePrice2Str);

        if (guidePrice1 < 0 || guidePrice2 < 0) {
            return StatusUtil.getFailedStatusWithMessage("价格必须为非负小数！");
        }

        if (CompanyDao.dao.getCompanyByCompanyId(companyId) == null) {
            return StatusUtil.getFailedStatusWithMessage("企业不存在！");
        }

        Product product;
        if (addOrProduct == TYPE_ADD) {
            product = new Product();
            product.setCompanyId(companyId);
            product.setProductId(productId);
        } else {
            product = ProductDao.dao.getProductByCompanyIdAndProductId(companyId, productId);
            if (product == null) {
                return StatusUtil.getFailedStatusWithMessage("产品不存在！");
            }
        }

        product.setType(type);
        product.setTypePinyin(Tools.toHanyuPinyin(type));
        product.setName(name);
        product.setNamePinyin(Tools.toHanyuPinyin(name));
        product.setUnit(unit);
        product.setProductNum(productNum);
        product.setUpperLimit(upperLimit);
        product.setLowerLimit(lowerLimit);
        product.setBrand(brand);
        product.setOriginPlace(originPlace);
        product.setSpecifications(specifications);
        product.setBarCode(barCode);
        product.setRemark(remark);
        product.setGuidePrice1(guidePrice1);
        product.setGuidePrice2(guidePrice2);
        product.setPrimaryDirectory(primaryDirectory);
        product.setSecondaryDirectory(secondaryDirectory);

        if (addOrProduct == TYPE_ADD) {
            return StatusUtil.getStatus(product.save(), "添加产品成功！", "添加产品失败！");
        } else {
            return StatusUtil.getStatus(product.update(), "更新产品成功！", "更新产品失败");
        }
    }

    public Map<String, Object> addProduct(
            String companyId,
            String type,
            String name,
            String unit,
            String productNum,
            String upperLimitStr,
            String lowerLimitStr,
            String brand,
            String originPlace,
            String specifications,
            String barCode,
            String remark,
            String guidePrice1Str,
            String guidePrice2Str,
            String primaryDirectory,
            String secondaryDirectory) {
        return addOrUpdateProduct(
                TYPE_ADD,
                companyId,
                "" + System.currentTimeMillis(),
                type,
                name,
                unit,
                productNum,
                upperLimitStr,
                lowerLimitStr,
                brand,
                originPlace,
                specifications,
                barCode,
                remark,
                guidePrice1Str,
                guidePrice2Str,
                primaryDirectory,
                secondaryDirectory
        );
    }

    public Map<String, Object> getProductsByCompanyId(String companyId) {
        if (Tools.checkParaIsInValidate(companyId)) {
            return StatusUtil.getFailedStatusWithMessage("参数无效！");
        }

        if (CompanyDao.dao.getCompanyByCompanyId(companyId) == null) {
            return StatusUtil.getFailedStatusWithMessage("企业不存在！");
        }

        List<Product> products = ProductDao.dao.getProductsByCompanyId(companyId);

        Map<String, Object> res = new HashMap<>();
        Map<String, Object> data = new HashMap<>();

        data.put("products", products);
        res.put("data", data);

        return StatusUtil.getSuccessStatusWithMessage(res, "获取产品成功！");
    }

    public Map<String, Object> updateProduct(
            String companyId,
            String productId,
            String type,
            String name,
            String unit,
            String productNum,
            String upperLimitStr,
            String lowerLimitStr,
            String brand,
            String originPlace,
            String specifications,
            String barCode,
            String remark,
            String guidePrice1Str,
            String guidePrice2Str,
            String primaryDirectory,
            String secondaryDirectory) {
        return addOrUpdateProduct(
                TYPE_UPDATE,
                companyId,
                productId,
                type,
                name,
                unit,
                productNum,
                upperLimitStr,
                lowerLimitStr,
                brand,
                originPlace,
                specifications,
                barCode,
                remark,
                guidePrice1Str,
                guidePrice2Str,
                primaryDirectory,
                secondaryDirectory);
    }

    public Map<String, Object> uploadProduct(
            String companyId,
            String productsStr) {
        if (Tools.checkParaIsInValidate(companyId, productsStr)) {
            return StatusUtil.getFailedStatusWithMessage("参数无效！");
        }

        if (CompanyDao.dao.getCompanyByCompanyId(companyId) == null) {
            return StatusUtil.getFailedStatusWithMessage("企业不存在！");
        }

        JSONArray array = JSONArray.parseArray(productsStr);
        if (array.size() > 200) {
            StatusUtil.getFailedStatusWithMessage("单次传输数据过大！");
        }

        for (int i = 0; i < array.size(); i++) {
            Product product = array.getObject(i, Product.class);
            product.setId(null);
            product.setCompanyId(companyId);
            product.setProductId("" + System.currentTimeMillis());
            product.setTypePinyin(Tools.toHanyuPinyin(product.getType()));
            product.setNamePinyin(Tools.toHanyuPinyin(product.getName()));
            if (!product.save()) {
                return StatusUtil.getFailedStatusWithMessage("上传失败！");
            }
        }

        return StatusUtil.getSuccessStatusWithMessage("上传成功！");
    }

    public Map<String, Object> uploadProductFinished(
            String username,
            double totalMoney) {
        if (Tools.checkParaIsInValidate(username)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        User user = UserDao.dao.getUserByUsername(username);
        Message message = new Message(
                username,
                "",
                1,
                totalMoney,
                0,
                0,
                0,
                Message.MESSAGE_TYPE_PRODUCTBATCH,
                user == null ? "" : user.getNickName(),
                "商品批处理");

        return StatusUtil.getStatus(
                message.save(),
                "商品批处理记录建立成功！",
                "商品批处理记录建立失败！");
    }

    public Map<String, Object> addFormula(
            String companyId,
            String combineId,
            String combineCountStr,
            String splitIds,
            String splitCounts) {
        if (Tools.checkParaIsInValidate(companyId, combineId, combineCountStr, splitIds, splitCounts)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        if (!CompanyService.getInstance().checkCompanyExists(companyId)) {
            return StatusUtil.getFailedStatusWithMessage("企业不存在！");
        }

        int combineCount = Tools.parseNatureInteger(combineCountStr);
        if (combineCount < 0) {
            return StatusUtil.getFailedStatusWithMessage("总成商品数量错误！");
        }

        if (ProductDao.dao.getProductByCompanyIdAndProductId(companyId, combineId) == null) {
            return StatusUtil.getFailedStatusWithMessage("总成商品不存在！");
        }

        if (FormulaDao.dao.getFormulaByCompanyIdAndCombineId(companyId, combineId) != null) {
            return StatusUtil.getFailedStatusWithMessage("该总成商品已存在拆分公式！");
        }

        Formula formula = new Formula();

        formula.setCompanyId(companyId);
        formula.setCombineId(combineId);
        formula.setCombineCount(combineCount);
        formula.setSplitIds(splitIds);
        formula.setSplitCounts(splitCounts);

        return StatusUtil.getStatus(formula.save(), "新建公式成功！", "新建公式失败！");
    }

    public Map<String, Object> deleteFormula(String companyId, String combineId) {
        if (Tools.checkParaIsInValidate(companyId, combineId)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        Formula formula = FormulaDao.dao.getFormulaByCompanyIdAndCombineId(companyId, combineId);

        if (formula == null) {
            return StatusUtil.getFailedStatusWithMessage("公式不存在！");
        }

        return StatusUtil.getStatus(formula.delete(), "公式删除成功！", "公式删除失败！");
    }

    public Map<String, Object> getFormulasByCompanyId(String companyId) {
        if (Tools.checkParaIsInValidate(companyId)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        if (!CompanyService.getInstance().checkCompanyExists(companyId)) {
            return StatusUtil.getFailedStatusWithMessage("企业不存在！");
        }

        List<Formula> tempFormulas = FormulaDao.dao.getFormulasByCompanyId(companyId);

        List<Formula> formulas = new ArrayList<>();
        for (Formula formula : tempFormulas) {
            if (formula.isValid()) {
                formulas.add(formula);
            } else {
                formula.delete();
            }
        }

        Map<String, Object> res = new HashMap<>();
        Map<String, Object> data = new HashMap<>();

        data.put("formulas", formulas);
        res.put("data", data);

        return StatusUtil.getSuccessStatusWithMessage(res, "获取公式成功！");
    }

    public Map<String, Object> combineProduct(String companyId, String combineId, String combineCountStr) {
        if (Tools.checkParaIsInValidate(companyId, combineId, combineCountStr)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        Formula formula = FormulaDao.dao.getFormulaByCompanyIdAndCombineId(companyId, combineId);

        if (formula == null) {
            return StatusUtil.getSuccessStatusWithMessage("公式不存在！");
        }

        int combineCount = Tools.parseNatureInteger(combineCountStr);
        if (combineCount < 1) {
            return StatusUtil.getFailedStatusWithMessage("装配数量错误！");
        }

        Product combineProduct = ProductDao.dao.getProductByCompanyIdAndProductId(companyId, formula.getCombineId());
        List<Product> splitProducts = formula.getSplitProducts();
        String[] splitCountArr = formula.getSplitCounts().split("#");
        List<Integer> needCounts = new ArrayList<>();
        double totalInprice = 0;

        //库存检测
        for (int i = 0; i < splitProducts.size(); i++) {
            Product product = splitProducts.get(i);
            int splitCount = Integer.parseInt(splitCountArr[i]);
            int needCount = splitCount * combineCount;
            totalInprice += needCount * product.getInPrice();
            needCounts.add(needCount);
            if (product.getCount() < needCount) {
                return StatusUtil.getFailedStatusWithMessage(
                        "商品" + product.getName() +
                                "库存不足，[库存:" + product.getCount() + "," +
                                "装配需求：" + needCount + "]");
            }
        }

        //更新拆分商品库存
        for (int i = 0; i < splitProducts.size(); i++) {
            Product product = ProductDao.dao.getProductByCompanyIdAndProductId(companyId, splitProducts.get(i).getProductId());
            int updateCount = product.getCount() - needCounts.get(i);
            product.setCount(updateCount);
            if (!product.update()) {
                return StatusUtil.getFailedStatusWithMessage("装配失败！");
            }
        }

        //更新总成商品
        int newCount = combineProduct.getCount() + (formula.getCombineCount() * combineCount);
        double newInPrice = combineProduct.getCount() * combineProduct.getInPrice() + totalInprice;
        newInPrice = Tools.formatDouble(newInPrice / newCount);
        combineProduct.setCount(newCount);
        combineProduct.setInPrice(newInPrice);

        return StatusUtil.getStatus(combineProduct.update(), "装配成功！[装配数量：" + formula.getCombineCount() * combineCount + "]", "装配失败！");
    }

    public Map<String, Object> splitProduct(
            String username,
            String companyId,
            String combineId,
            String splitCountStr,
            String splitInPrices) {
        if (Tools.checkParaIsInValidate(username, companyId, combineId, splitCountStr, splitInPrices)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        Formula formula = FormulaDao.dao.getFormulaByCompanyIdAndCombineId(companyId, combineId);

        if (formula == null) {
            return StatusUtil.getFailedStatusWithMessage("公式不存在！");
        }

        int splitCount = Tools.parseNatureInteger(splitCountStr);
        if (splitCount < 1) {
            return StatusUtil.getFailedStatusWithMessage("拆分数量错误！");
        }

        Product combineProduct = ProductDao.dao.getProductByCompanyIdAndProductId(companyId, formula.getCombineId());
        List<Product> splitProducts = formula.getSplitProducts();
        String[] splitCountArr = formula.getSplitCounts().split("#");
        String[] splitInpriceArr = splitInPrices.split("#");

        int needCount = splitCount * formula.getCombineCount();
        if (combineProduct.getCount() < needCount) {
            return StatusUtil.getFailedStatusWithMessage(
                    "总成商品" + combineProduct.getName() +
                            "库存不足，[库存:" + combineProduct.getCount() + "," +
                            "拆分需求：" + needCount + "]");
        }

        combineProduct.setCount(combineProduct.getCount() - needCount);
        if (!combineProduct.update()) {
            return StatusUtil.getFailedStatusWithMessage("拆分失败！");
        }

        double splitLoss = formula.getCombineCount() * combineProduct.getInPrice();

        for (int i = 0; i < splitProducts.size(); i++) {
            Product product = ProductDao.dao.getProductByCompanyIdAndProductId(companyId, splitProducts.get(i).getProductId());
            int curSplitCount = Integer.parseInt(splitCountArr[i]);
            int newCount = product.getCount() + curSplitCount * splitCount;
            double curSplitInprice = Double.parseDouble(splitInpriceArr[i]);
            splitLoss -= curSplitInprice * curSplitCount;
            double newInPrice = product.getCount() * product.getInPrice() + curSplitCount * curSplitInprice * splitCount;
            newInPrice = Tools.formatDouble(newInPrice / newCount);
            product.setCount(newCount);
            product.setInPrice(newInPrice);
            if (!product.update()) {
                return StatusUtil.getFailedStatusWithMessage("拆分失败！");
            }
        }

        User user = UserDao.dao.getUserByUsername(username);
        splitLoss *= splitCount;
        splitLoss = Tools.formatDouble(splitLoss);

        Message message = new Message(
                username,
                "",
                1,
                splitLoss,
                0,
                0,
                0,
                Message.MESSAGE_TYPE_SPLITMONEY,
                user == null ? "" : user.getNickName(),
                "拆分差价");

        if (!message.save()) {
            return StatusUtil.getFailedStatusWithMessage("拆分差额记录建立失败！");
        }

        return StatusUtil.getSuccessStatusWithMessage("拆分成功！");
    }

    public Map<String, Object> countProduct(String username, String companyId, String productsStr) {
        if (Tools.checkParaIsInValidate(companyId, productsStr)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        if (!CompanyService.getInstance().checkCompanyExists(companyId)) {
            return StatusUtil.getFailedStatusWithMessage("企业不存在！");
        }

        JSONArray array = JSONArray.parseArray(productsStr);

        double totalValue = 0;
        for (int i = 0; i < array.size(); i++) {
            JSONObject obj = array.getJSONObject(i);
            String productId = obj.getString("product_id");
            int lowerLimit = obj.getIntValue("lower_limit");
            int upperLimit = obj.getIntValue("upper_limit");
            int count = obj.getIntValue("count");
            int countNum = obj.getIntValue("count_num");
            int sanbao = obj.getIntValue("sanbao");
            Product product = ProductDao.dao.getProductByCompanyIdAndProductId(companyId, productId);
            if (product == null) {
                return StatusUtil.getFailedStatusWithMessage("商品[" + productId + "]不存在！");
            }

            if (countNum - product.getSanbao() < 0) {
                return StatusUtil.getFailedStatusWithMessage("商品[" + product.getName() + "]盘点数量不合法！");
            }

            if (count != product.getCount() || sanbao != product.getSanbao()) {
                return StatusUtil.getFailedStatusWithMessage("商品[" + product.getName() + "]本地数据与服务器数据不符，请更新数据！");
            }

            product.setLowerLimit(lowerLimit);
            product.setUpperLimit(upperLimit);
            product.setCount(countNum - product.getSanbao());
            totalValue += (countNum - count - sanbao) * product.getInPrice();

            if (!product.update()) {
                return StatusUtil.getFailedStatusWithMessage("盘点失败！");
            }
        }

        User user = UserDao.dao.getUserByUsername(username);

        Message message = new Message(
                username,
                "",
                1,
                totalValue,
                0,
                0,
                0,
                Message.MESSAGE_TYPE_PRODUCTCOUNT,
                user == null ? "" : user.getNickName(),
                "商品盘点");

        if (!message.save()) {
            return StatusUtil.getFailedStatusWithMessage("商品盘点记录建立失败！");
        }

        return StatusUtil.getSuccessStatusWithMessage("盘点成功！");
    }

    public Map<String, Object> sanbaoMove(
            String companyId,
            String productsStr,
            String moveTypeStr,
            String moveCountStr) {
        if (Tools.checkParaIsInValidate(companyId, productsStr, moveTypeStr, moveCountStr)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        if (!CompanyService.getInstance().checkCompanyExists(companyId)) {
            return StatusUtil.getFailedStatusWithMessage("企业不存在！");
        }

        //0:出库 三包库-->库存
        //1:入库 库存-->三包库
        int moveType = Tools.parseNatureInteger(moveTypeStr);
        if (moveType != 0 && moveType != 1) {
            return StatusUtil.getFailedStatusWithMessage("移库类型错误！");
        }

        JSONArray array = JSONArray.parseArray(productsStr);
        String[] moveCountArr = moveCountStr.split("#");
        List<Product> checkedProducts = new ArrayList<>();

        for (int i = 0; i < array.size(); i++) {
            String productId = array.getJSONObject(i).getString("product_id");
            Product product = ProductDao.dao.getProductByCompanyIdAndProductId(companyId, productId);
            if (product == null) {
                return StatusUtil.getFailedStatusWithMessage("商品[" + productId + "]不存在！");
            }
            int moveCount = Integer.parseInt(moveCountArr[i]);
            if (moveType == 0) {
                //0:出库 三包库-->库存
                if (moveCount > product.getSanbao()) {
                    return StatusUtil.getFailedStatusWithMessage("商品[" + productId + "]:三包库存不足[三包库存:" + product.getSanbao() + ",需求数:" + moveCount + "]");
                }
                product.setCount(product.getCount() + moveCount);
                product.setSanbao(product.getSanbao() - moveCount);
            } else {
                //1:入库 库存-->三包库
                if (moveCount > product.getCount()) {
                    return StatusUtil.getFailedStatusWithMessage("商品[" + productId + "]:库存不足[库存:" + product.getCount() + ",需求数:" + moveCount + "]");
                }
                product.setCount(product.getCount() - moveCount);
                product.setSanbao(product.getSanbao() + moveCount);
            }
            checkedProducts.add(product);
        }

        if (checkRepeatProduct(checkedProducts)) {
            return StatusUtil.getFailedStatusWithMessage("存在重复商品记录，请核验后提交！");
        }

        moveTypeStr = moveType == 0 ? "出库" : "入库";
        for (Product product : checkedProducts) {
            if (!product.update()) {
                return StatusUtil.getFailedStatusWithMessage(moveTypeStr + "失败！");
            }
        }

        return StatusUtil.getSuccessStatusWithMessage(moveTypeStr + "成功！");
    }

    public Map<String, Object> updateHistoryProducts(String historyProductsStr, int type) {
        if (Tools.checkParaIsInValidate(historyProductsStr)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        JSONArray array = JSONArray.parseArray(historyProductsStr);

        for (int i = 0; i < array.size(); i++) {
            JSONObject obj = array.getJSONObject(i);
            String sourceCompanyId = obj.getString("source_company_id");
            String targetCompanyId = obj.getString("target_company_id");
            String sourceProductId = obj.getString("source_product_id");
            String targetProductId = obj.getString("target_product_id");
            int historyType = obj.getIntValue("type");
            int sourceScale = obj.getIntValue("source_scale");
            int targetScale = obj.getIntValue("target_scale");
            double price = obj.getDoubleValue("history_price");
            HistoryProduct historyProduct = ProductDao.dao.getHistoryProduct(
                    sourceCompanyId,
                    targetCompanyId,
                    sourceProductId,
                    targetProductId,
                    historyType,
                    type);
            boolean isSave = false;
            if (historyProduct == null) {
                historyProduct = new HistoryProduct();
                isSave = true;
            }
            historyProduct.setType(historyType);
            historyProduct.setSourceCompanyId(sourceCompanyId);
            historyProduct.setTargetCompanyId(targetCompanyId);
            historyProduct.setSourceProductId(sourceProductId);
            historyProduct.setTargetProductId(targetProductId);
            historyProduct.setSourceScale(sourceScale);
            historyProduct.setTargetScale(targetScale);
            historyProduct.setHistoryPrice(price);
            boolean res;
            if (isSave) {
                res = historyProduct.save();
            } else {
                res = historyProduct.update();
            }
            if (!res) {
                return StatusUtil.getFailedStatusWithMessage("历史价格更新失败！");
            }
        }

        return StatusUtil.getSuccessStatusWithMessage("历史价格更新成功！");
    }

    public Map<String, Object> getAllHistoryProducts(
            String sourceCompanyId,
            String targetCompanyId,
            String productIds,
            int type) {
        if (Tools.checkParaIsInValidate(sourceCompanyId, targetCompanyId, productIds)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        String[] productIdArr = productIds.split("#");
        List<HistoryProduct> historyProducts = new ArrayList<>();
        for (String productId : productIdArr) {
            HistoryProduct historyProduct = ProductDao.dao.getHistoryProductBySourceProductId(
                    sourceCompanyId,
                    targetCompanyId,
                    productId,
                    type);

            if (historyProduct == null) {
                historyProduct = new HistoryProduct();
                historyProduct.setType(type);
                historyProduct.setSourceCompanyId(sourceCompanyId);
                historyProduct.setTargetCompanyId(targetCompanyId);
                historyProduct.setSourceProductId(productId);
                historyProduct.save();
            }

            historyProducts.add(historyProduct);
        }

        Map<String, Object> res = new HashMap<>();
        Map<String, Object> data = new HashMap<>();

        data.put("allHistoryProducts", historyProducts);
        res.put("data", data);

        return StatusUtil.getSuccessStatusWithMessage(res, "历史价格获取成功！");
    }

    public Map<String, Object> deleteProduct(String companyId, String productId) {
        if (Tools.checkParaIsInValidate(companyId, productId)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        Product product = ProductDao.dao.getProductByCompanyIdAndProductId(companyId, productId);

        if (product == null) {
            return StatusUtil.getFailedStatusWithMessage("商品[" + productId + "]不存在！");
        }

        if (product.getCount() != 0 || product.getSanbao() != 0) {
            return StatusUtil.getFailedStatusWithMessage("商品[" + productId + "]库存数[" + product.getCount() + "]或三包数[" + product.getSanbao() + "]不为0，无法删除！");
        }

        if (!product.delete()) {
            return StatusUtil.getFailedStatusWithMessage("删除失败！");
        }

        return StatusUtil.getSuccessStatusWithMessage("删除成功！");
    }

    public Map<String, Object> refreshProducts(String companyId, String productIds) {
        if (Tools.checkParaIsInValidate(companyId, productIds)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        String[] productIdArr = productIds.split("#");
        List<Product> products = new ArrayList<>();

        for (String productId : productIdArr) {
            Product product = ProductDao.dao.getProductByCompanyIdAndProductId(companyId, productId);
            if (product != null) {
                products.add(product);
            }
        }

        Map<String, Object> res = new HashMap<>();
        Map<String, Object> data = new HashMap<>();

        data.put("products", products);
        res.put("data", data);

        return StatusUtil.getSuccessStatusWithMessage(res, "刷新成功！");
    }

    public Map<String, Object> getFormulaInfo(String companyId, String combineId) {
        if (Tools.checkParaIsInValidate(companyId, combineId)) {
            return StatusUtil.getFailedStatusWithInvalidParaMessage();
        }

        Formula formula = FormulaDao.dao.getFormulaByCompanyIdAndCombineId(companyId, combineId);
        if (formula == null) {
            return StatusUtil.getFailedStatusWithMessage("公式不存在！");
        }

        if (!formula.isValid()) {
            return StatusUtil.getFailedStatusWithMessage("总成商品或拆分商品不存在！");
        }

        Map<String, Object> res = new HashMap<>();
        Map<String, Object> data = new HashMap<>();

        data.put("formula", formula);
        data.put("combineProduct", formula.getCombineProduct());
        data.put("splitProducts", formula.getSplitProducts());
        res.put("data", data);

        return StatusUtil.getSuccessStatusWithMessage(res, "获取成功");
    }
}
